package edu.hubu.talentmanagementsystem.controller;

import edu.hubu.talentmanagementsystem.common.CommonResult;
import edu.hubu.talentmanagementsystem.exception.InformationNotFoundException;
import edu.hubu.talentmanagementsystem.exception.TokenIsInvalidException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.web.servlet.error.AbstractErrorController;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author moonlan
 * date 2021/3/3 下午8:04
 */
@SuppressWarnings(value = "unused")
@RestController
public class ErrorController extends AbstractErrorController {

    @Value("${application.environment}")
    private String environment;

    public ErrorController(ErrorAttributes errorAttributes) {
        super(errorAttributes);
    }

    @RequestMapping("${server.error.path:${error.path:/error}}")
    public CommonResult error(HttpServletRequest request) {
        HttpStatus httpStatus = getStatus(request);
        Map<String, Object> body = getErrorAttributes(
                request,
                ErrorAttributeOptions.of(
                        ErrorAttributeOptions.Include.STACK_TRACE,
                        ErrorAttributeOptions.Include.BINDING_ERRORS, ErrorAttributeOptions.Include.EXCEPTION,
                        ErrorAttributeOptions.Include.MESSAGE
                )
        );

        if (isDevelopment(environment)) {
            return new CommonResult().setMsg("开发环境，查看data属性获取异常值").setData(body);
        } else {
            String exception = (String) body.get("exception");
            if (exception.equals(InformationNotFoundException.class.getName())) {
                return new CommonResult().setMsg(body.get("message").toString())
                        .setCode(404).setCurrentPage(1).setTotalPage(1);
            } else if (exception.equals(TokenIsInvalidException.class.getName())) {
                return new CommonResult().setMsg(body.get("message").toString())
                        .setCode(401).setCurrentPage(1).setTotalPage(1);
            } else {
                return new CommonResult().setMsg(body.get("message").toString())
                        .setCode(httpStatus.value()).setCurrentPage(1).setTotalPage(1);
            }
        }
    }

    private boolean isDevelopment(String environment) {
        return "dev".equals(environment);
    }

    @Override
    public String getErrorPath() {
        return null;
    }
}
